package handle

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	. "leaf/cache"
	. "leaf/common"
	"leaf/core/cache"
	"leaf/core/conf"
	. "leaf/core/error"
	"leaf/core/gate"
	"leaf/core/log"
	. "leaf/core/msg"
	"leaf/core/tool"
	"leaf/model"
	"leaf/pb"
)

func LoginHandler(agent gate.Agent, msg *PMsg) *Error {
	c2s := msg.C2S().(*pb.C2S_LogicAuth)
	session := c2s.GetSession()
	log.Release("LoginHandler start,session:%v", session)
	if session == "" {
		log.Release("LoginHandler err:%v", Error_LoginSessionErr)
		return Error_LoginSessionErr
	}

	var rds = cache.GetInstance()
	if rds == nil {
		log.Release("LoginHandler err:%v", Error_DBErr)
		return Error_DBErr
	}

	data, err := rds.Get(fmt.Sprintf(GAMER_LOGIN_SESSION, GetKeyPrefix(), session)).Result()
	if tool.RedisError(err) {
		log.Release("LoginHandler err:%v", Error_DBErr)
		return Error_DBErr
	}
	loginStatus := &pb.LoginStatus{}
	if !tool.ParseDBStr(data, loginStatus) {
		log.Release("LoginHandler err:%v", Error_DBErr)
		return Error_DBErr
	}
	if loginStatus.GetStatus() != 2 {
		log.Release("LoginHandler err:%v", Error_LoginStatusErr)
		return Error_LoginStatusErr
	}

	gamer := model.NewGamer(loginStatus.GetRole().GetUserid())
	userModel := gamer.GetUserModel()
	if userModel == nil {
		log.Release("LoginHandler err:%v", Error_LoginStatusErr)
		return Error_DBErr
	}
	statusModel := gamer.GetStatusModel()
	if statusModel == nil {
		log.Release("LoginHandler err:%v", Error_LoginStatusErr)
		return Error_DBErr
	}

	statusModel.Status.Lid = proto.Int32(conf.Config.ServerId)
	statusModel.Save()
	if statusModel.Status.GetPid() != 0 {
		//
	}

	if oldAgent := gate.GetAgent(userModel.User.GetUserid()); oldAgent != nil {
		// 	发送退出消息
		//	oldAgent.SendMsg("xxx")
		oldAgent.Close()
	}
	agent.SetUserData(gamer)
	gate.AddAgent(userModel.User.GetUserid(), agent)

	s2c := msg.S2C().(*pb.S2C_LogicAuth)
	s2c.Data = userModel.User
	log.Release("LoginHandler success,user:%v", s2c.Data)

	return nil
}
